﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace Cxx.IOC
{
    /// <summary>
    /// 依赖注入管理
    /// </summary>
    public class IocManager
    {
        private readonly IUnityContainer container;

        // 同步锁对象
        private static readonly object syncRoot = new object();

        private static IocManager instance;

        private IocManager()
        {
            container = new UnityContainer();
        }

        /// <summary>
        /// 创建IOC管理对象单例
        /// </summary>
        public static IocManager Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new IocManager();
                        }
                    }
                }
                return instance;
            }
        }

        /// <summary>
        /// 获取访问实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T ResolveIntance<T>()
        {
            return container.Resolve<T>();
        }

        /// <summary>
        /// 判断是否已经注册
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool IsRegistered(Type type)
        {
            return container.IsRegistered(type);
        }

        /// <summary>
        /// 注册实例
        /// </summary>
        /// <typeparam name="TFrom"></typeparam>
        /// <typeparam name="TTo"></typeparam>
        public IocManager RegisterType<TFrom, TTo>() where TTo : TFrom
        {
            container.RegisterType<TFrom, TTo>();
            return instance;
        }
    }
}
